package dao.Product;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Product;
import abstractFactory.Factory;

public class ProductDAOJPA implements ProductDAO{
	static EntityManager manager;

	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}

	public boolean save(Product product) {
		try	{
			getManager().getTransaction().begin();		
			getManager().persist(product);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean update(Product product){
		try{
			getManager().getTransaction().begin();
			getManager().merge(product);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean delete(Product product){
		try {
			getManager().getTransaction().begin();
			Product p = getManager().find(Product.class,product.getId());
			getManager().remove(p);
			getManager().getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<Product> getAllProducts(){
		Query query = (Query) getManager().createQuery("SELECT p FROM Product p where p.active = 1" );
		@SuppressWarnings("unchecked")
		List<Product> produtos =  query.getResultList();
		return produtos;
	}

	public List<Product> getProductsByCategory(int categoryId){
		Query query = (Query) getManager().createQuery("SELECT p FROM Product p join p.categories cat where cat.id = :category");
		query.setParameter("category", categoryId);
		@SuppressWarnings("unchecked")
		List<Product> produtos =  query.getResultList();
		return produtos;
	}

	public Long getTotalProducts(){
		Query query = (Query) getManager().createQuery("SELECT count(p) FROM Product p where p.active = 1" );
		Long total = (Long) query.getSingleResult();
		return total;
	}

	public Long getTotalProductsByCategory(int categoryId){
		Query query = (Query) getManager().createQuery("SELECT count(p) FROM Product p join p.categories cat where cat.id = :category and p.active = 1" );
		query.setParameter("category", categoryId);
		Long total = (Long) query.getSingleResult();
		return total;
	}

	public Product getProductById(int productId){
		try {
			Product product = getManager().find(Product.class, productId);
			return product;
		} catch (Exception e) {
			return null;				
		}
	}
}
